package Solution221_240;

import java.util.ArrayList;
import java.util.List;

public class Solution229 {
    /**
     * 思路就是三个不同的数抵消一下
     * 超过三分之一的 最多两个
     *
     * @param nums
     * @return
     */
    public static List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums.length < 1) {
            return res;
        }
        int num1 = nums[0];
        int count1 = 0;
        int num2 = nums[0];
        int count2 = 0;

        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            if (temp == num1) {
                count1++;
            } else if (temp == num2) {
                count2++;
            } else if (count1 == 0) {
                count1 = 1;
                num1 = temp;
            } else if (count2 == 0) {
                count2 = 1;
                num2 = temp;
            } else {
                count1--;
                count2--;
            }
        }
        count1 = 0;
        count2 = 0;
        int numSum = nums.length / 3;
        for (int i = 0; i < nums.length; i++) {
            int temp = nums[i];
            if (temp == num1) {
                count1++;
            } else if (temp == num2) {
                count2++;
            }
        }
        if (count1 > numSum) {
            res.add(num1);
        }
        if (num1 != num2 && count2 > numSum) {
            res.add(num2);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 1, 3, 3, 2, 2, 2};
        List<Integer> res = majorityElement(nums);
        System.out.println(res);
    }
}
